<?php


namespace App\Models\CacheModel\zl1_relation;


use app\common\lib\Util;
use App\Models\Api\BaseCache;
use think\Log;
use traits\model\SoftDelete;
use AstroTool\Cache\CacheManage;

class Zl1RelationAnalysisIdea extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl1_relation_analysis_idea';

    protected $cacheModel = 'relation_analysis.my_idea';

    protected $deleteTime = 'delete_time';

    use SoftDelete;

    /**
     * 写入我的理想型 数据 和 添加计算队列
     * @param $data
     * @return bool
     */
    public function SaveDataAndQueue($data): bool
    {
        try
        {
            $id = $this->insertGetId([
                'uid' => $data['uid'],
                'rids' => $data['rids'],
                'gid' => $data['gid'],
                'tag_info' => $data['tag_info'],
                'order_num' => $data['order_num'],
                'status' => 1,
                'create_time' => $data['create_time'],
            ]);
            // 列表添加
            $this->listDataAdd($data['uid'], [$id => $id]);
            if (Util::getVips($data['uid'], 24, 0))
            {
                $queueDelay = 0;
            }
            // 添加计算队列
            Util::queuePush('relation_analysis_idea', [
                'id' => $id,
                'uid' => $data['uid'],
                'rids' => $data['rids'],
                'order_id' => $data['order_num'],
                'tag_info' => $data['tag_info'],
                'is_update' => false,
                'push_switch' => true // 是否发送消息与推送
            ], $queueDelay ?? null);

            // 删除用户解锁 方案缓存
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('unlock_case', $data['uid'])
                ->rmCache('unlock_case');

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl1RelationAnalysisIdea model => SaveDataAndQueue()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

            return false;
        }
    }

    /**
     * 更新我的理想型 数据
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, array $data)
    {
        try
        {
            $this->where('id', $id)->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl1RelationAnalysisIdea model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

            return false;
        }
    }

    /**
     * 删除我的理想型 数据
     * @param int $id
     * @param int $uid
     * @return bool
     */
    public function DeleteUpdate(int $id, int $uid)
    {
        try
        {
            $this->where('id', $id)->update(['delete_time' => time()]);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();

            $this->listDataDel($uid, [$id]);

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl1RelationAnalysisIdea model => DeleteUpdate()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

            return false;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $field = 'uid,rids,rid_num,gid,tag_info,order_num,content,start_time,status,create_time,update_time';
        try
        {
            if ($ids)
            {
                $where = ['id' => ['in', $ids]];
            } else
            {
                $where = ['uid' => $type[0]];
            }

            $data = $this
                ->field($field)
                ->where($where)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        foreach ($resData as $id => $orderItemData)
        {
            $resData[$id] = arrayKeyData2int($orderItemData, ['id', 'uid', 'rid_num', 'status', 'gid', 'start_time', 'create_time', 'update_time']);

            if (isset($orderItemData['content']) && $orderItemData['content'])
            {
                $resData[$id]['content'] = json_decode($orderItemData['content'], true);
            }

            if (isset($orderItemData['tag_info']) && $orderItemData['tag_info'])
            {
                $resData[$id]['tag_info'] = json_decode($orderItemData['tag_info'], true);
            }

            if (isset($orderItemData['rids']) && $orderItemData['rids'])
            {
                $rids = explode(',', $orderItemData['rids']);
                $rids = array_map('intval', $rids);

                $resData[$id]['rids'] = $rids;
            }
        }

        return $resData;
    }

    /**
     * 获取列表信息
     * @param $id
     * @param string $sortKey
     * @param array $field
     * @param int $type
     * @param string $sort
     * @param int $isSortNum
     * @param string $listKey
     * @param string $detailsKey
     * @return array|mixed
     * @throws \Exception
     */
    public function getListPage($id, $sortKey = 'id', $field = [], int $type = 0, $sort = 'desc', $isSortNum = 1, $listKey = 'list', $detailsKey = 'list_details')
    {
        $pageData = parent::getListPage($id, $sortKey, $field, $type, $sort, $isSortNum, $listKey, $detailsKey); //

        $resData = $pageData['data'];
        foreach ($resData as $id => $orderItemData)
        {
            $resData[$id] = arrayKeyData2int($orderItemData, ['id', 'uid', 'rid_num', 'status', 'gid', 'start_time', 'create_time', 'update_time']);

            if (isset($orderItemData['content']) && $orderItemData['content'])
            {
                $resData[$id]['content'] = json_decode($orderItemData['content'], true);
            }

            if (isset($orderItemData['tag_info']) && $orderItemData['tag_info'])
            {
                $resData[$id]['tag_info'] = json_decode($orderItemData['tag_info'], true);
            }

            if (isset($orderItemData['rids']) && $orderItemData['rids'])
            {
                $rids = explode(',', $orderItemData['rids']);
                $rids = array_map('intval', $rids);

                $resData[$id]['rids'] = $rids;
            }
        }

        $pageData['data'] = $resData;

        return $pageData;
    }

    /**
     * 获取解锁方案
     * @param int $uid
     * @return mixed
     * @throws \Exception
     */
    public function getUnlockCaseList(int $uid)
    {
        $caseDataStr = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('unlock_case', $uid)
            ->setCacheType('string')->getDataAndSet(function () use ($uid)
            {
                try
                {
                    $data = $this->where('uid', $uid)->where(['status' => ['in', [1, 2]]])->column('tag_info');
                    $resData = [];
                    foreach ($data as $caseItem)
                    {
                        $caseData = json_decode($caseItem, true);

                        $caseItemData = sprintf("%d:%d:%d:%d:%d:%d:%d", $caseData[1], $caseData[2], $caseData[3], $caseData[4], $caseData[5], $caseData[6], $caseData[7]);

                        if (!in_array($caseItemData, $resData, true))
                        {
                            $resData[] = $caseItemData;
                        }
                    }

                    return json_encode($resData, JSON_UNESCAPED_UNICODE);
                }
                catch (\Exception $e)
                {
                    Log::write('Zl1RelationAnalysisIdea model => getUnlockCaseList()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                    return '';
                }
            }, [], 'unlock_case');

        return json_decode($caseDataStr, true);
    }
}
